package com.corn.juc.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function : 证明 ReentrantLock 可重入
 * @since : 2020/12/28 15:38
 */

public class ReentrantLockDemo {
    static class TestDemo implements Runnable {
        private final ReentrantLock lock = new ReentrantLock();

        private void method1() {
            lock.lock();
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " invoke method1 ...");
                TimeUnit.SECONDS.sleep(1);
                method2();
            } catch (InterruptedException e) {
                e.printStackTrace();
                lock.lock();
                lock.lock();
            } finally {
                lock.unlock();
            }
        }

        private void method2() {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " invoke method2 ...");
            } finally {
                lock.unlock();
            }
        }

        @Override
        public void run() {
            method1();
        }
    }

    public static void main(String[] args) {
        TestDemo testDemo = new TestDemo();
        new Thread(testDemo).start();
        new Thread(testDemo).start();
    }
}
